package com.jackrain.nea.fc.dl.service;


import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.util.TypeUtils;
import com.jackrain.nea.common.*;
import com.jackrain.nea.dl.common.utils.esutil.ConvertQueryListUtil;
import com.jackrain.nea.dl.common.utils.esutil.ElasticsearchUtil;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.fc.dl.api.WmsTranOutSaveCmd;
import com.jackrain.nea.fc.dl.mapper.WmsTranMapper;
import com.jackrain.nea.fc.utils.Constants;
import com.jackrain.nea.fc.utils.UserInformation;
import com.jackrain.nea.sys.CommandAdapter;
import com.jackrain.nea.util.ApplicationContextHandle;
import com.jackrain.nea.util.RuntimeCompute;
import com.jackrain.nea.util.ValueHolder;
import com.jackrain.nea.web.face.User;
import com.jackrain.nea.web.query.DefaultWebEvent;
import com.jackrain.nea.web.query.QuerySessionImpl;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * @author xuxinshuai
 * @date 2018/05/05
 * hhh
 */
@Slf4j
@Component
@Service(protocol = "dubbo", validation = "true", version = "1.0", group = "dl")
public class WmsTranOutSaveCmdImpl extends CommandAdapter implements WmsTranOutSaveCmd {


    @Autowired
    PostDubbleEvent postDubbleEvent;
    @Autowired
    PostHandleEvent postHandleEvent;
    @Autowired
    QueryCpUtil postQueryEvemt;
    @Autowired
    QueryUserUtil postUserEvent;


    @Autowired
    private ElasticsearchUtil esUtil;

    @Autowired
    private ConvertQueryListUtil convertQLUtil;

    @Autowired
    private BtranEsName btranEsName;

    private Logger accesLogger = LoggerFactory.getLogger(Constants.ACCESS_PARAM_LOGGER);

    @Override
    public ValueHolder execute(HashMap map) throws NDSException {

        ValueHolder vh = new ValueHolder();
        WmsTranMapper wmsTranMapper = ApplicationContextHandle.getBean(WmsTranMapper.class);

        JSONObject param = JSON.parseObject(JSON.toJSONStringWithDateFormat(map.get("param"), "yyyy-MM-dd HH:mm:ss", SerializerFeature.WriteMapNullValue), Feature.OrderedField);
        if (null == param || param.size() == 0) {
            throw new NDSException("参数格式错误！");
        }
        log.info("WmsTranOutSaveCmdImpl-->param-->{}",param);
//        log.debug("----------出库回传（调拨出库单）----------" + param);
        RuntimeCompute runtimeCompute = ApplicationContextHandle.getBean("runtimeCompute");
        runtimeCompute.startRuntime();

        JSONArray dataArray = param.getJSONArray("data");
        JSONArray succesIdArray = new JSONArray();
        JSONArray queryDataArray = new JSONArray();
        JSONArray errArray = new JSONArray();

        for (int i = 0; i < dataArray.size(); i++) {

            JSONObject dataJo = dataArray.getJSONObject(i);
            JSONObject oldJo = dataJo.getJSONObject("DL_B_TRAN_OUT");
            JSONArray purInItemArray = dataJo.getJSONArray("DL_B_TRAN_OUT_V_ITEM_SKU");
            String billnoid = oldJo.getString("ID");
            try {

                String billno = oldJo.getString("BILL_NO");
                String orig_ecode = oldJo.getString("ORIG_ECODE");
                //改成ES查询
//                Long objid = null;
//                JSONObject jsonObject = es(billno);
//                List<Long> longs = convertQLUtil.selectId(jsonObject.toString());
//                if (null != longs && longs.size() > 0) {
//                    objid = longs.get(0);
//
//                } else {
//                    throw new NDSException(billno + "单据编号查询不到对应的ID和BILL_TYPE");
//                }
                Long objid = wmsTranMapper.selectTranoutBillnoId(billno);
                if (objid == null) {
                    throw new NDSException(billno + "找不到对应单据ID！");
                }

                JSONObject fixColumn = dataConversion(oldJo, purInItemArray, objid);
                User user = postUserEvent.getUser(UserInformation.USER_NAME);
                JSONObject resultJson = new JSONObject();
                //查询是否管控仓
                JSONObject whereJo = new JSONObject();
                whereJo.put("ECODE", orig_ecode);
                JSONObject result = postQueryEvemt.queryCP("CP_C_STORE", "ISWMS", whereJo);
                if (result != null) {
                    String iswms = TypeUtils.castToString(result.getString("ISWMS"));
                    if ("1".equals(iswms)) {
                        resultJson.put("isWMSCheck", "Y");
                    }else{
                        resultJson.put("isWMSCheck", "N");
                    }
                }else{
                    log.error("查不到该仓库"+orig_ecode);
                    throw new NDSException("查不到该仓库"+orig_ecode);
                }
                resultJson.put("objid", objid);
                resultJson.put("fixcolumn", fixColumn);
                resultJson.put("table", "DL_B_TRAN_OUT");
                accesLogger.info("WmsTranOutSaveCmdImpl--resultJson-->{}",resultJson);
//                log.info("resultJson==>" + resultJson.toString());
                QuerySessionImpl querySession = new QuerySessionImpl(user);
                DefaultWebEvent event = new DefaultWebEvent("dlOrderOut", new HashMap(16));
                event.put("param", resultJson);
                event.setParameter("command", "com.jackrain.nea.dl.tran.api.BtranoutbufferSaveCmd:1.0:dl");
                event.setParameter("table", "DL_B_TRAN_OUT");
                querySession.setEvent(event);
                //1. 调用标准服务
                JSONObject retJo = postHandleEvent.executePostHandle(resultJson, querySession, event, "save");
                accesLogger.info("WmsTranOutSaveCmdImpl--retJo-->{}",retJo);

                if (retJo.get("code") != null && (int) retJo.get("code") < 0) {
                    throw new NDSException("保存失败:" + retJo.get("message") + retJo.get("error") + retJo.get("data"));
                }
//                //2.发出服务
//                resultJson.put("objid", objid);
////                resultJson.put("IS_BOX_SEND", "Y");
//                resultJson.put("STORE_DATE", dateToStrLong(oldJo.getDate("DATE_OUT")));
//                log.info("发出resultJson==>" + resultJson.toString());
//                event.put("param", resultJson);
//                event.setParameter("command", "com.jackrain.nea.dl.tran.api.BtranoutSendCmd:1.0:dl");
//                event.setParameter("table", "DL_B_TRAN_OUT");
//                event.setParameter("webaction", "DL_B_TRAN_OUT_SEND_TRAFFIC_CONFIRM");
//
//                querySession.setEvent(event);
//                JSONObject subJo = postHandleEvent.executePostHandle(resultJson, querySession, event, "webaction");
//
//                if (subJo.get("code") != null && (int) subJo.get("code") < 0) {
//                    throw new NDSException("发出失败:" + subJo.get("message") + subJo.get("error") + subJo.get("data"));
//                }
                succesIdArray.add(billnoid);
                queryDataArray.add(resultJson);

            } catch (Exception e) {

                JSONObject errrobj = new JSONObject();
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                e.printStackTrace(pw);
                if (e instanceof NDSException) {
                    errrobj.put("message", e.getMessage());
                } else {
                    errrobj.put("message", sw.toString());
                }
                errrobj.put("key", billnoid);
                errArray.add(errrobj);
            }

        }

        if (errArray.size() > 0) {
            vh.put("error", errArray);
            vh.put("successIds", succesIdArray);
            vh.put("code", -1);
        } else {
            vh.put("successIds", succesIdArray);
            vh.put("code", 0);
        }
        vh.put("queryDataArray", queryDataArray);
        Double spendTime = runtimeCompute.endRuntime();
        vh.put("spendtime", spendTime);
//        log.debug("---------调拨出库单执行时间--------->>" + spendTime);

        return vh;

    }

    /**
     * 数据整合
     *
     * @param oldJo          主表数据
     * @param purInItemArray 子表数据
     * @return JSONObject
     */
    public JSONObject dataConversion(JSONObject oldJo, JSONArray purInItemArray, Long objid) {

        WmsTranMapper wmsTranMapper = ApplicationContextHandle.getBean(WmsTranMapper.class);

        JSONObject newJo = new JSONObject();
        newJo.put("BILL_DATE", dateToStrLong(oldJo.getDate("DATE_OUT")));
        newJo.put("REMARK", oldJo.getString("REMARK"));
        newJo.put("varchar1", oldJo.getString("WMS_BILL_NO"));

        BigDecimal sumQty = BigDecimal.ZERO;
        BigDecimal sumAmt = BigDecimal.ZERO;

        JSONArray itemArray = new JSONArray();
        for (int a = 0; a < purInItemArray.size(); a++) {

            JSONObject oldItemJo = purInItemArray.getJSONObject(a);
            JSONObject newItemJo = new JSONObject();
            String skuecode = oldItemJo.getString("SKU");
            Long itemId = wmsTranMapper.selectTranId(objid, skuecode);
            if (itemId == null) {
                throw new NDSException(skuecode + "找不到对应单据明细ID！");
            }
            newItemJo.put("ID", itemId);

            JSONObject whereJo5 = new JSONObject();
            whereJo5.put("ECODE", skuecode);
            whereJo5.put("CP_C_DISTRIB_ID", "0");
            JSONObject cpmap5 = postQueryEvemt.queryCP("PS_C_SKU", "ID", whereJo5);
            if (null == cpmap5) {
                throw new NDSException(skuecode + "查询不到对应的条码ID！");
            }
            Long skuId = TypeUtils.castToLong(cpmap5.getLong("ID"));
            newItemJo.put("PS_C_SKU_ID", skuId);
            newItemJo.put("QTY_OUT", oldItemJo.getString("QTY_OUT"));
            //查询PRICE_LIST
            BigDecimal priceList = wmsTranMapper.selectPriceList(itemId);

            BigDecimal qty_out = oldItemJo.getBigDecimal("QTY_OUT");
            BigDecimal amount = priceList.multiply(qty_out);
            newItemJo.put("AMT_OUT", amount);

            sumQty = sumQty.add(oldItemJo.getBigDecimal("QTY_OUT"));
            sumAmt = sumAmt.add(amount);
            itemArray.add(newItemJo);

        }

        newJo.put("SUM_QTY_OUT", sumQty);
        newJo.put("SUM_AMT_LIST_OUT", sumAmt);

        JSONObject fixColumn = new JSONObject();
        fixColumn.put("DL_B_TRAN_OUT", newJo);
        fixColumn.put("DL_B_TRAN_OUT_V_ITEM_SKU", itemArray);

        return fixColumn;

    }

    /**
     * ES查询
     *
     * @param billNo 单据编号
     * @return id
     */
    public JSONObject es(String billNo) {
        JSONObject bill_no = esUtil.generateMatch("BILL_NO", billNo);
        List<JSONObject> terms = esUtil.packageTerm(bill_no);
        JSONObject jsonObject = null;
        try {
            jsonObject = esUtil.searchAllDataByTerms(btranEsName.getIndex(),
                    btranEsName.getOuttype(), "1", "10000", terms);
            log.debug("es_jsonObject->" + jsonObject);
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return jsonObject;
    }

    private JSONObject billdata(JSONObject esData) {
        JSONObject hits = esData.getJSONObject("hits");
        JSONArray hitsArray = hits.getJSONArray("hits");
        JSONObject sourceJson = hitsArray.getJSONObject(0);

        JSONObject source = sourceJson.getJSONObject("_source");

        return source;
    }


    /**
     * 将长时间格式时间转换为字符串 yyyy-MM-dd HH:mm:ss
     *
     * @param dateDate
     * @return
     */
    public static String dateToStrLong(java.util.Date dateDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        String dateString = formatter.format(dateDate);
        return dateString;
    }


}